<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>原型模式</title>
    <style>
        *{
            padding: 0;
            margin: 0;
        }
        canvas {
            display: block;
            border: 1px solid black;
            margin: 0 auto;
        }
    </style>
</head>
<body>
    <canvas id="canvas" width="500" height="400"></canvas>
    <script>
        let canvas = document.getElementById('canvas');
        let ctx = canvas.getContext('2d');
        let circleArr = [];
        function Circle(x, y, r) { 
            this.x = x - (window.innerWidth - 500)/2;
            this.y = y;
            this.r = r;
            this.color = this.getColor();
            circleArr.push(this);
         };
         Circle.prototype.getColor = function () { 
                let random = Math.floor(Math.random()*0xFFFFFF).toString(16);
                if (random.length === 6) {
                    return '#' + random;
                }
                else {
                    this.getColor();
                }
        };
        Circle.prototype.render = function () { 
            ctx.beginPath();
            ctx.arc(this.x, this.y, this.r, 0, 2*Math.PI);
            ctx.fillStyle = this.color;
            ctx.fill();
         };
         Circle.prototype.update = function () { 
            this.r --;
            if (this.r > 0) return true;
         }
        // 绑定鼠标移动事件
        canvas.onmousemove = function (e) {
            // 创建小球
            setTimeout(() => {
                new Circle(e.clientX, e.clientY, Math.random()*50+10);
            }, 200); 
        };
        setInterval(_ => {
            ctx.clearRect(0, 0, 500, 400);
            circleArr.forEach(item => {
                item.update() && item.render();
            })
        }, 19)
    </script>
    
</body>
</html>